import axios from 'axios'
// import store from '@/store'
import { Toast } from 'vant'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base api url + request url
  withCredentials: false, // send cookies when cross-domain requests
  timeout: 60 * 1000 // request timeout
})

// request拦截器
service.interceptors.request.use(
  (config: any) => {
    return config
  },
  (error: any) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// respone拦截器
service.interceptors.response.use(
  (response: any) => {
    const res = response
    if (res.status && res.status !== 200) {
      return Promise.reject(res || 'error')
    } else {
      return Promise.resolve(res)
    }
  },
  (error: any) => {
    console.log('err' + error) // for debug

    /* if (!window.navigator.onLine) {
      window.location.href = `${location.origin}${location.pathname}#/nonet`
      return
    } */

    if (error?.stack?.indexOf('timeout') > -1) {
      Toast.fail('接口超时')
      return
    } else if (error?.message?.includes('Network')) {
      Toast.fail('网络异常')
      return
    } else if (error && (error.code === 'ECONNABORTED' || error.message?.includes('code 500'))) {
      Toast.fail('服务响应异常，请稍后重试')
      return
    }

    return Promise.reject(error)
  }
)

export default service
